package server;

import java.util.*;

import msgs.*;
/**
 * Handles query messages from the Client
 * Team 9: Andrew Hayworth, Brian Parrella, Ryan Kortmann, Nina Papa
 * @author Andrew Hayworth
 */
public class ClientQuerier extends Thread implements TTConstants {
	private QueryMsg qmsg;
	
	public ClientQuerier(ClientMsg qmsg) {
		this.qmsg = (QueryMsg) qmsg;
	}
	
	public void run() {
		// check if they're who they say they are
		if (!(Arrays.equals(qmsg.getClientKey(), TTServer.connTable.get(qmsg.getName()).getClientKey()))) {
			qmsg.setResponse(Responses.DENY);
			ClientSender.outQ.add((ClientMsg) qmsg);
			return;
		}
		
		// first see what they want
		switch (qmsg.getAction()) {
		case QUERY:
			// ok, return the status of the user they want
			if (TTServer.connTable.containsKey(qmsg.getWantsUser())) {
				qmsg.setResponse(Responses.ONLINE);
			}
			else {
				qmsg.setResponse(Responses.OFFLINE);
			}
			break;
		case QUERY_GROUP:
			// oh, they want a list of statuses. oK!
			HashMap<String, Integer> hold = qmsg.getUserList(); // why? concurrent modification exceptions
			HashMap<String, Integer> hnew = new HashMap<String, Integer>();	// i dont want synchronized modifications, either.
			// create a hashmap of the online status of their buddies
			for (String s : hold.keySet()) {
				if (TTServer.connTable.containsKey(s)) {
					hnew.put(s, 1);
				}
				else {
					hnew.put(s, 0);
				}
			}
			qmsg.setUserList(hnew);
		}
		ClientSender.outQ.add((ClientMsg) qmsg);
	}
}
